using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace TemplatePlugin
{
    public partial class CreateTemplateForm : Form
    {
        public CreateTemplateForm()
        {
            InitializeComponent();
        }

        public CreateTemplateForm(FileInfo fi) : this()
        {
            // fill in the form fields with the saved template
            using (StreamReader sr = fi.OpenText())
            {
                this.templateContentTextBox.Text = sr.ReadToEnd();
            }
            this.templateNameTextBox.Text = fi.Name;
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            try
            {
                // verify the template name is a valid file name
                FileInfo fi = new FileInfo(TemplatePlugin.PluginsFolder + this.templateNameTextBox.Text.Trim());
                if (fi.Exists)
                    if (MessageBox.Show("Do you want to overwrite the existing template?", "File Exists", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) != DialogResult.OK)
                        return;

                // save the tempalte
                using (StreamWriter sw = fi.CreateText())
                {
                    sw.Write(this.templateContentTextBox.Text);
                }
                
                // and return OK
                this.DialogResult = DialogResult.OK;
            }
            catch (Exception)
            {
                // probably the template name was incorrect so just display that warning for now
                MessageBox.Show("A valid template name is required.", "Enter valid template name", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                this.templateNameTextBox.Focus();
                this.templateNameTextBox.SelectAll();
                return;
            }
        }
    }
}